<?php

/**

 * 物品管理
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn>
 */

namespace Home\Controller;

use Think\Controller;

class GoodsController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        $this->limit = 20;

        //获取类别
        $this->cates = M('goods_type')->select();
    }

    //查询
    public function index() {
        $p = I('get.p', 1, 'intval');
        $limit = 20;

        if (isset($_GET['type']) && I('type')) {
            $map['type'] = I('type');
            $this->type = I('type');
        }
        if (isset($_GET['name']) && I('name')) {
            $goodsId = M('goods')->where(array('name' => array('like', '%' . I('name') . '%')))->getField('id');
            $map['goods_id'] = $goodsId;
            $this->name = I('name');
        }
        if (isset($_GET['number']) && I('number')) {
            $map['number'] = I('number');
            $this->number = I('number');
        }
//print_r($map);
        if (I('get.goodsType') == 2) {
            //出库查询
            $data = M('goods_out')->where($map)->page($p, $limit)->select();
        } else {
            //入库查询
            $data = M('goods_put')->where($map)->page($p, $limit)->select();
        }
        $this->gType = isset($_GET['goodsType']) ? I('goodsType') : 1;


        $page = ($p - 1) * $limit + 1;
        foreach ($data as $key => $row) {
            $data[$key]['page'] = $page++;
        }

        $count = M('goods_put')->count();
        $this->page = $this->pageLists($count, $limit);
        $this->data = $data;
        $this->display();
    }

    //采购
    public function buyGoods() {

        $this->display();
    }

    //入库
    public function putGoods() {
        if (IS_AJAX) {
            if (I('type') == 1) {
                //信息化
                $number = 'XXH' . date('Ymd');
            } else {
                //低值
                $number = 'DZ' . date('Ymd');
            }
            $pdata['number'] = I('number') ? I('number') : $number;
            $pdata['create_time'] = I('create_time') ? strtotime(I('create_time')) : time();

            for ($i = 0; $i < count(I('name')); $i++) {
                //添加物品表
                $data['name'] = I('name')[$i];
                $data['count'] = I('count')[$i];
                $data['type'] = I('type');
                //去重
                $umap['name'] = I('name')[$i];
                $umap['type'] = I('type');
                $count = M('goods')->where($umap)->find();
                if (empty($count)) {
                    $goods_id = M('goods')->add($data);
                } else {
                    //加库存
                    $add['count'] = $count['count'] + I('count')[$i];
                    M('goods')->where($umap)->save($add);
                    $goods_id = $count['id'];
                }

                if ($goods_id) {
                    //入库表
                    $pdata['goods_id'] = $goods_id;
                    $pdata['model'] = I('model')[$i];
                    $pdata['unit'] = I('unit')[$i];
                    $pdata['count'] = I('count')[$i];
                    $pdata['price'] = I('price')[$i];
                    $pdata['remark'] = I('remark')[$i];
                    $pdata['type'] = I('type');
                    $res = M('goods_put')->add($pdata);
                }
            }

            if ($res) {
                $return['status'] = 1;
                $return['info'] = '提交成功';
            } else {
                $return['status'] = 0;
                $return['info'] = '提交失败';
            }
            $this->ajaxReturn($return);
        }
        $this->display();
    }

    //出库
    public function outGoods() {
        if (IS_AJAX) {
            $data['user_id'] = session('user_id');
            $data['type'] = I('type');
            $data['create_time'] = time();
            $data['status'] = 0;    //未出库
            for ($i = 0; $i < count(I('goods_id')); $i++) {
                $data['goods_id'] = I('goods_id')[$i];
                $data['count'] = I('count')[$i];
                $data['remark'] = I('remark')[$i];
                //去重
                $map = $data['goods_id'];
                $map['user_id'] = session('user_id');
                $map['status'] = 0;
                $one = M('goods_out')->where($map)->find();
                if (!$one) {
                    $res = M('goods_out')->add($data);
                } else {
                    $return['info'] = '请勿重复提交';
                    $return['status'] = 0;
                }
            }
            $return['info'] = $res ? '提交成功' : '提交失败';
            $return['url'] = $res ? U('useGoods') : '';
            $this->ajaxReturn($return);
        }

        //获取物品
        $goods = M('goods')->select();

        $this->goods = $goods;
        $this->display();
    }

    //盘点
    public function checkGoods() {
        $p = I('get.p', 1, 'intval');
        $limit = 20;

        if (isset($_GET['type']) && I('type')) {
            $map['type'] = I('type');
            $this->type = I('type');
        }

        if (isset($_GET['mode']) && I('mode')) {
            if (isset($_GET['start']) && I('start')) {
                $map['create_time'] = array('between', [strtotime(I('start')), strtotime(I('end'))]);
                $this->start = I('start');
                $this->end = I('end');
            }

            if (I('mode') == 1) {
                //入库盘点
                $goods = M('goods_put')->where($map)->page($p, $limit)->select();
                $count = M('goods_put')->where($map)->count();
                $this->page = $this->pageLists($count, $limit);
            }
            if (I('mode') == 2) {
                //出库
                $goods = M('goods_out')->where($map)->page($p, $limit)->select();
                $count = M('goods_out')->where($map)->count();
                $this->page = $this->pageLists($count, $limit);
            }

            foreach ($goods as $key => $row) {
                $goods[$key]['name'] = getGoodsName($row['goods_id']);
                if (I('mode') == 1) {
                    $goods[$key]['put'] = $row['count'];
                } else {
                    $goods[$key]['out'] = $row['count'];
                    $goods[$key]['model'] = getGoodsModel($row['goods_id']);
                    $one = M('goods_put')->where('goods_id=' . $row['goods_id'])->find();
                    $goods[$key]['unit'] = $one['unit'];
                }
                $goods[$key]['date'] = date('Y-m-d', $row['create_time']);
            }

            //合计
            if (I('mode') == 1) {
                //入库
                $goodsAll = M('goods_put')->where($map)->select();
            }
            if (I('mode') == 2) {
                //出库
                $goodsAll = M('goods_out')->where($map)->select();
            }
            $total = 0;
            foreach ($goodsAll as $key => $row) {
                $total += $row['count'];
            }
            $this->total = $total;
            $this->mode = I('mode');
        } else {
            $goods = M('goods')->where($map)->page($p, $limit)->select();
            $count = M('goods')->where($map)->count();
            $this->page = $this->pageLists($count, $limit);

            foreach ($goods as $key => $row) {
                $goods[$key]['model'] = getGoodsModel($row['id']);
                $one = M('goods_put')->where('goods_id=' . $row['id'])->find();
                $goods[$key]['unit'] = $one['unit'];
                $goods[$key]['price'] = $one['price'];

                //入库数量 取当月
                $begin = strtotime(date('Y-m-01 00:00:00'));
                $end = strtotime(date("Y-m-31 23:59:59"));
                $goods[$key]['put'] = getGoodsCount(2, $row['id'], $begin, $end);

                //出库数量 取当月
                $goods[$key]['out'] = getGoodsCount(1, $row['id'], $begin, $end);

                //损耗
                $goods[$key]['lose'] = abs($goods[$key]['put'] - $goods[$key]['out'] - $row['count']);

                //计算期末余额  add zyh 2018-07-24
                //判断上月是否计划
                $prevbegin = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
                $prevend = strtotime(date("Y-m-d 23:59:59", strtotime(-date('d') . 'day')));
                $put = getGoodsCount(1, $row['id'], $prevbegin, $prevend);
                $out = getGoodsCount(2, $row['id'], $prevbegin, $prevend);
                if (($month > substr($row['edit_date'], 0, 7)) || ($row['eidt_date'] == '0000-00-00')) {
                    $sData['final_balance'] = $row['begin_balance'] + $put - $out;
                    $sData['edit_date'] = date('Y-m-30', strtotime('-1 month'));
                    $sData['begin_balance'] = $sData['final_balance'];
                    $sMap['id'] = $row['id'];
                    M('goods')->where($sMap)->save($sData);
                }
            }
            $this->mode = 0;
        }

        $this->goods = $goods;
        $this->display();
    }

    //领用
    public function useGoods() {
        //获取user_priv和user_priv_other
        $row = M('user')->field('user_id,user_name,user_priv,user_priv_other')->where('user_id="' . session('user_id') . '"')->find();
        $userpriv = $row['user_priv'] . ',' . $row['user_priv_other'];
        $userpriv = explode(',', $userpriv);

        //取物品管理员priv_id
        $map['_string'] = ' priv_name like "%库房%" or priv_name like "%固资%" or priv_name like "%固定资产%"';
        $privIds = M('user_priv')->where($map)->getField('user_priv', true);

        $isAdmin = 0;
        foreach ($userpriv as $key => $row) {
            if (in_array($row, $privIds)) {
                $isAdmin = 1;
            }
        }

        unset($map);
        //搜索
        if (isset($_GET['user_id']) && I('user_id')) {
            $user_id = M('user')->where('user_name="' . I('user_id') . '"')->getField('user_id');
            $map['user_id'] = $user_id;
            $this->userId = I('user_id');
        }
        if (isset($_GET['start']) && I('start')) {
            $map['create_time'] = array('between', [strtotime(I('start')), strtotime(I('end'))]);
            $this->start = I('start');
            $this->end = I('end');
        }
        if (isset($_GET['type']) && I('type')) {
            $map['type'] = I('type');
            $this->type = I('type');
        }
        if (isset($_GET['status']) && I('status') >= 0) {
            $map['status'] = I('status');
            $this->status = I('status');
        }
        if (isset($_GET['name']) && I('name')) {
            $ids = M('goods')->where('name like "%' . I('name') . '%"')->getField('id', true);
            if (!is_array($ids)) {
                $ids[] = $ids;
            }
            $map['goods_id'] = array('in', $ids);
            $this->name = I('name');
        }

        $p = I('get.p');
        $limit = 20;

        if ($isAdmin != 1) {
            $map['user_id'] = session('user_id');
        }
        $goods = M('goods_out')->where($map)->page($p, $limit)->select();

        $count = M('goods_out')->where($map)->count();
        $this->page = $this->pageLists($count, $limit);

        $this->user = session('user_id');
        $this->isAdmin = $isAdmin;
        $this->goods = $goods;
        $this->display();
    }

    //获取物品
    public function getGoodsData() {
        $type = I('type');
        $data = M('goods')->where('type=' . $type)->select();
        $this->ajaxReturn($data);
    }

    //获取单个物品信息
    public function getGoodsInfo() {
        $id = I('get.id');
        $info = M('goods_put')->where('goods_id=' . $id)->find();
        $info['total'] = M('goods')->where('id=' . $id)->getField('count');
        $this->ajaxReturn($info);
    }

    public function upload() {
        $config = array(
            'maxSize' => 3145728, //3M
            'rootPath' => './Public/Uploads/goods/',
            'exts' => array('xls', 'xlsx', 'csv'),
            'subName' => '',
        );
        $upload = new \Think\Upload($config); // 实例化上传类
        // 上传文件 

        $file = $_POST['imgfile'];
        $info = $upload->uploadOne($_FILES['imgfile']);
        $url = "/Public/Uploads/goods/" . $info['savepath'] . $info['savename'];
        if (!$info) {
            $this->ajaxReturn("false", "EVAL");
        } else {
            $result = $this->checkFile($url);
            $this->ajaxReturn($result);
        }
    }

    //存入数据表
    public function saveExcel($data, $url) {
        //存入数据库
        foreach ($data[0] as $key => $row) {
            //取标题外边
            if ($key > 1) {
                if (strpos($row['A'], '信息') !== false) {
                    $type = 1;
                    if (ltrim($row['B'], '&gt;') == '') {
                        $number = 'XXH' . date('Ymd');
                    } else {
                        $number = $row['B'];
                    }
                } else {
                    $type = 2;
                    if (ltrim($row['B'], '&gt;') == '') {
                        $number = 'DZ' . date('Ymd');
                    } else {
                        $number = $row['B'];
                    }
                }
                if (ltrim($row['C'], '&gt;') == '') {
                    $time = time();
                } else {
                    $time = strtotime(ltrim($row['C'], '&gt;'));
                }

                $data['type'] = $type;
                $data['name'] = $row['D'];
                $data['count'] = $row['F'];
                $map['name'] = $row['D'];
                $map['type'] = $type;
                $one = M('goods')->where($map)->find();
                if (!$one) {
                    $goods_id = M('goods')->add($data);
                } else {
                    //加库存
                    $add['count'] = $one['count'] + $row['F'];
                    M('goods')->where($map)->save($add);
                    $goods_id = $one['id'];
                }

                if ($goods_id) {
                    $pdata['goods_id'] = $goods_id;
                    $pdata['number'] = $number;
                    $pdata['type'] = $type;
                    $pdata['model'] = $row['E'];
                    $pdata['unit'] = $row['G'];
                    $pdata['count'] = $row['F'];
                    $pdata['price'] = $row['H'];
                    $pdata['remark'] = $row['I'];
                    $pdata['create_time'] = $time;
                    $res = M('goods_put')->add($pdata);
                }
            }
        }
        if ($res) {
            $return['error'] = 0;
            @unlink('.' . $url);
        } else {
            $return['error'] = 1;
        }

        return $return;
    }

    //验证excel文件
    public function checkFile($fileUrl) {
        if ($fileUrl) {
            $goods = importExcel('.' . $fileUrl);
            $result = $this->saveExcel($goods, $fileUrl);
        } else {
            $result['error'] = 1;
            $result['info'] = '文件地址不存在';
        }
        return $result;
    }

    //确认出库
    public function confirm() {
        $id = I('id');  //出库表id
        $num = I('num');
        $one = M('goods_out')->find($id);

        if (!isset($_GET['type'])) {
            $data['status'] = 1;
        $data['auditor'] = session('user_id');
        $data['auditor_time'] = time();
            $data['real_count'] = $num;
        } else {
        $data['count'] = $num;
        }

        $res = M('goods_out')->where('id=' . $id)->save($data);

        if ($res !== false) {
            if (isset($_GET['type']) && I('type')) {
                $return['info'] = '修改成功';
            } else {
            $return['info'] = '出库成功';

            //减库存
                $goods = M('goods')->find($one['goods_id']);
                $dec['count'] = $goods['count'] - $num;
                M('goods')->where('id=' . $one['goods_id'])->save($dec);
            }
        } else {
            $return['info'] = '操作失败';
        }

        $this->ajaxReturn($return);
    }

    //删除
    public function delete() {
        $id = I('id');

        if (isset($_GET['type']) && I('type')) {
            //删除出库物品
            $resOut = M('goods_out')->delete($id);
        } else {
            //减少物品表数量
            $row = M('goods_put')->find($id);
            $goods = M('goods')->find($row['goods_id']);
            $dec['count'] = $goods['count'] - $row['count'];
            $res = M('goods')->where('id=' . $row['goods_id'])->save($dec);

            //删除物品入库表
            if ($res !== false) {
                $resPut = M('goods_put')->delete($id);
}
        }

        $return['status'] = ($resPut || $resOut) !== false ? 1 : 0;

        $this->ajaxReturn($return);
    }

    
}
